package com.beiye.drivertransport.utils;

import android.os.Environment;

import com.beiye.drivertransport.thirdparty.tbs.LoadFileModel;
import com.beiye.drivertransport.thirdparty.tbs.SuperFileView2;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class FileParseUtil {
    private static SuperFileView2 superFileView2=null;
    private static String fileName="";


    public static String getFilePath(SuperFileView2 mSuperFileView2,String url, String name){
        superFileView2=mSuperFileView2;
        fileName=name+"."+getFileType(url);

        File filedir=new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/007/");
        if(!filedir.exists()){
            filedir.mkdir();
        }

        File cacheFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/007/" + fileName);
        if (cacheFile.exists()) {
            return cacheFile.toString();
        } else {
            return url;
        }
    }

    public static void getFilePathAndShowFile(SuperFileView2 mSuperFileView2,String filePath) {

        if (filePath.contains("http")) {//网络地址要先下载
            // showAlertDialog(mSuperFileView2);
            downLoadFromNet(filePath,mSuperFileView2);
        } else {
            mSuperFileView2.displayFile(new File(filePath));
        }
    }

    /***
     * 获取缓存目录
     *
     * @param url
     * @return*/
    private static File getCacheDir(String url) {
        return new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/007/");
    }

    /***
     * 绝对路径获取缓存文件
     *
     * @param url
     * @return*/
    public static File getCacheFile(String url) {
        /*String[] strs=url.split("/");
        String fileName=strs[strs.length-1];*/
        File cacheFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/007/"
                + fileName);
        //LogUtils.e(TAG, "缓存文件 = " + cacheFile.toString()+"  "+fileName);
        return cacheFile;
    }

    private static void downLoadFromNet(final String url,SuperFileView2 mSuperFileView2) {
        //showLoadingDialog("文件下载中...");
        //1.网络下载、存储路径、
        File cacheFile = getCacheFile(url);
        if (cacheFile.exists()) {
            if (cacheFile.length() <= 0) {
                cacheFile.delete();
                return;
            }
        }

        LoadFileModel.loadPdfFile(url, new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

                boolean flag;
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                try {
                    ResponseBody responseBody = response.body();

                    is = responseBody.byteStream();
                    long total = responseBody.contentLength();

                    File file1 = getCacheDir(url);
                    if (!file1.exists()) {
                        file1.mkdirs();
                        //LogUtils.e(TAG, "创建缓存目录： " + file1.toString());
                    }


                    //fileN : /storage/emulated/0/pdf/kauibao20170821040512.pdf
                    File fileN = getCacheFile(url);//new File(getCacheDir(url), getFileName(url))


                    if (!fileN.exists()) {
                        boolean mkdir = fileN.createNewFile();
                    }
                    fos = new FileOutputStream(fileN);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                        // circularProgressView.setProgress(progress);
                        // tv1.setText(progress+"%");
                    }
                    fos.flush();
                    //2.ACache记录文件的有效期
                    mSuperFileView2.displayFile(fileN);
                } catch (Exception e) {

                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException e) {
                    }
                    try {
                        if (fos != null)
                            fos.close();
                    } catch (IOException e) {
                    }
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                File file = getCacheFile(url);
                if (!file.exists()) {
                    file.delete();
                }
            }

        });
    }

    public static void releaseFileView(){
        if (superFileView2 != null) {
            superFileView2.onStopDisplay();
            superFileView2=null;
        }
    }

    /***
     * 根据链接获取文件名（带类型的），具有唯一性
     *
     * @param url
     * @return*/

    private static String getFileName(String url) {
       /* String fileName = Md5Tool.hashKey(url) + "." + getFileType(url);*/
        String[] strs=url.split("/");
        String str=strs[strs.length-1];
        String[] strs2=str.split("/?");
        String fileName=strs2[0];
        return fileName;
    }

    /***
     * 获取文件类型
     * @return*/

    private static String getFileType(String url) {
        /*String str = "";

        if (TextUtils.isEmpty(paramString)) {
            LogUtils.e(TAG, "paramString---->null");
            return str;
        }
        LogUtils.e(TAG, "paramString:" + paramString);
        int i = paramString.lastIndexOf('.');
        if (i <= -1) {
            LogUtils.e(TAG, "i <= -1");
            return str;
        }


        str = paramString.substring(i + 1);
        LogUtils.e(TAG, "paramString.substring(i + 1)------>" + str);
        return str;*/
        String[] strs=url.split("/");
        String str=strs[strs.length-1];
        String[] strs2=str.split("\\?");
        String[] strs3=strs2[0].split("\\.");
        return strs3[1];
    }

}
